
        var loggedIn = true;

        var paBookmark = "/icons/bookmark.png";
        var paBookmarked = "/icons/bookmarked.png";
        var paLoggedOut = "/icons/loggedout.png";
	var titleBookmark = "Bookmark this page - GBX+";
	var titleBookmarked = "Edit bookmark - GBX+"
	var titleLoggedOut = "Log in to Google Bookmarks";
	var portsArray = new Array();

	var menuAddBookmarkId;
	var menuRefreshId;
        
        
        /* UI */
	function setStarVisibility(tabId) {
	  if (showPageAction == "true")
	    chrome.pageAction.show(tabId)
	  else chrome.pageAction.hide(tabId);
	}

        function updateStars() {
            chrome.windows.getAll({populate: true}, function(windows) {
                for (var i = 0; i < windows.length; i++) {
                    for (var j = 0; j < windows[i].tabs.length; j++) {
                        updateStar(windows[i].tabs[j].id);
                    }
                }
            });
        }

        function updateStar(tabid) {
            chrome.tabs.get(tabid, function(currentTab) {
		setStarVisibility(currentTab.id);
		
                if (!loggedIn) {
                    chrome.pageAction.setIcon({
                        tabId: currentTab.id,
                        path: paLoggedOut
                    });
		    chrome.pageAction.setTitle({
			tabId: currentTab.id,
			title: titleLoggedOut
		    });
                    return;
                }

                chrome.bookmarks.search(currentTab.url, function(results) {
                    var bmfound = false;
                    for (var i = 0; i < results.length; i++) {
                        if (results[i].url == currentTab.url) {
                            bmfound = true;
                        }
                    }

                    if (bmfound) {
                        chrome.pageAction.setIcon({
                            tabId: currentTab.id,
                            path: paBookmarked
                        });
			chrome.pageAction.setTitle({
			    tabId: currentTab.id,
			    title: titleBookmarked
			});
                    } else {
                        chrome.pageAction.setIcon({
                            tabId: currentTab.id,
                            path: paBookmark
                        });
			chrome.pageAction.setTitle({
			    tabId: currentTab.id,
			    title: titleBookmark
			});
                    }
                });
            });
        }

        /* Utility */
        function currentTime() {
            var currentTime = new Date()
            var hours = currentTime.getHours()
            var minutes = currentTime.getMinutes()

            var suffix = "AM";
            if (hours >= 12) {
                suffix = "PM";
                hours = hours - 12;
            }
            if (hours == 0) {
                hours = 12;
            }

            if (minutes < 10)
                minutes = "0" + minutes

            return hours + ":" + minutes + " " + suffix;
        }

        function goToLogin() {
            chrome.tabs.create({ url: "http://www.google.com/bookmarks" });
        }

        function addbookmark() {
            chrome.windows.getCurrent(function(currentWindow) {
                chrome.tabs.getSelected(currentWindow.id, function(currentTab) {
                    console.log("Adding bookmark: " + currentTab.url);

                    var newWindow = window.open("http://www.google.com/bookmarks/mark?op=edit&output=popup&bkmk=" + encodeURIComponent(currentTab.url) + "&title=" + encodeURIComponent(currentTab.title), "bkmk_popup", "left=" + ((screen.width / 2) - 350) + ",top=" + ((screen.height / 6)) + ",height=450px,width=700px,resizable=1,alwaysRaised=1");
		    newWindow.focus();
                //    window.setTimeout(function() { newWindow.focus(); newWindow.onunload = requestBookmarks; }, 1000);
                });
            });
        }


	function postOptions (port) {
	  port.postMessage({	"message": "options",
				"delimiter": delimiter,
				"sortorder": sortorder,
				"checkfrequency": checkfrequency,
				"folder": userFolderName,
				"show": showPageAction
			  });
	}

	function portOnMessage(port, data) {
		console.log("Received message: " + data.message + " from " + port.sender.tab.url);
		
                if (data.message && data.message == 'openoptions') {
                    chrome.tabs.create({ url: '/html/options.html' });
                } else if (data.message && data.message == 'refreshbookmarks') {
                    requestBookmarks();
                } else if (data.message && data.message == 'getoptions') {
                    postOptions(port);
                } else if (data.message && data.message == 'saveoptions') {
		    var restart = saveOptions(data);
		    loadOptions();
		    for (var i = 0; i < portsArray.length; i++)
		      if (portsArray[i].portId_ != port.portId_)
			postOptions(portsArray[i]);
		
		  updateStars();
		}
            }

	function portOnDisconnect (port) {
	  portsArray.splice(portsArray.indexOf(port),1);
	}

	function contextMenusCallback()	{
	  if (chrome.extension.lastError)
	    console.log("Error when creating context menus: "+chrome.extension.lastError);
	}

	function onContextMenus (onClickData)
	{
	  if (onClickData.menuItemId == menuAddBookmarkId) {
	    //console.log("Context menu - Add Bookmark");
	    addbookmark();
	  }
	  if (onClickData.menuItemId == menuRefreshId) {
	    //console.log("Context menu - Refresh");
	    requestBookmarks();
	  }
	}

	function init() {
	  loadOptions();
	  window.setTimeout(requestBookmarks, 5000);
	}

        /* Events */
        chrome.tabs.onUpdated.addListener(function(tabid) {
            //console.log("Tab updated...");
            updateStar(tabid);
        });

        
            chrome.pageAction.onClicked.addListener(function(tab) {
                addbookmark();
            });

        
        chrome.extension.onConnect.addListener(function(port) {
            console.log("connected");
	    portsArray.push(port);
            port.onMessage.addListener(function (data) { portOnMessage (port, data); });
	    port.onDisconnect.addListener(function (port) { portOnDisconnect(port); });
        });

	menuAddBookmarkId = chrome.contextMenus.create({"title": "Add bookmark",
							"onclick": onContextMenus
							}, contextMenusCallback);

	menuRefreshId = chrome.contextMenus.create({"title": "Refresh bookmarks",
						    "onclick": onContextMenus
						    }, contextMenusCallback);

document.addEventListener("DOMContentLoaded", function() {
  init();
});